package com.changgou.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fescar.spring.annotation.GlobalTransactional;
import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.order.config.RabbitMQConfig;
import com.changgou.order.dao.*;
import com.changgou.order.pojo.*;
import com.changgou.order.service.CartService;
import com.changgou.order.service.OrderService;
import com.changgou.pay.feign.WXPayFeign;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private WXPayFeign wxPayFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    /**
     * 查询全部列表
     *
     * @return
     */
    @Override
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     *
     * @param order
     */
    @Override
    @GlobalTransactional(name = "order_add")
    public String add(Order order) {
//        orderMapper.insert(order);
        //获取购物车的相关数据 redis
        Map cartMap = cartService.list(order.getUsername());
        List<OrderItem> orderItemList = (List<OrderItem>) cartMap.get("orderItemList");

        //统计计算 总金额 总商品数量
        //填充订单数据 并保存到tb_order
        order.setTotalNum((Integer) cartMap.get("totalNum"));
        order.setTotalMoney((Integer) cartMap.get("totalMoney"));
        order.setPayMoney((Integer) cartMap.get("totalMoney"));
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setBuyerRate("0"); //0 未评价
        order.setSourceType("1"); //1 来源web
        order.setOrderStatus("0"); //0 订单未完成  1 订单已完成  2 订单已退货
        order.setPayStatus("0"); //0 订单未支付  1 订单已支付
        order.setConsignStatus("0"); //0 订单未发货 1 订单已发货
        String orderId = idWorker.nextId() + "";
        order.setId(orderId);
        orderMapper.insertSelective(order);

        //填充订单项的数据 并保存到tb_order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setId(idWorker.nextId() + "");
            orderItem.setIsReturn("0"); //0 未退货  1 已退货
            orderItem.setOrderId(orderId);
            orderItemMapper.insertSelective(orderItem);
        }

        //扣减库存 增加销量
        Result result = skuFeign.decrCount(order.getUsername());
        if (!result.isFlag()) {
            throw new RuntimeException(result.getMessage());
        }

//        int i=10/0;

        //下单成功 增加积分
        Task task = new Task();
        task.setCreateTime(new Date());
        task.setUpdateTime(new Date());
        task.setMqExchange(RabbitMQConfig.EX_BUYING_ADDPOINTUSER);
        task.setMqRoutingkey(RabbitMQConfig.CG_BUYING_ADDPOINT_KEY);

        Map map = new HashMap();
        map.put("username", order.getUsername());
        map.put("orderId", orderId);
        map.put("point", order.getPayMoney());
        task.setRequestBody(JSON.toJSONString(map));
        taskMapper.insertSelective(task);

        //清空购物车数据
        redisTemplate.delete("CART_" + order.getUsername());

        rabbitTemplate.convertAndSend(RabbitMQConfig.EX_ORDER_PAY_OVERTIME, "", order.getId());

        return orderId;
    }


    /**
     * 修改
     *
     * @param order
     */
    @Override
    public void update(Order order) {
        orderMapper.updateByPrimaryKey(order);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(String id) {
        System.out.println(id);
        orderMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Order>) orderMapper.selectAll();
    }

    /**
     * 条件+分页查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @Override
    public Page<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return orders;
    }

    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        //查询数据库订单信息
        Order order = orderMapper.selectByPrimaryKey(orderId);
        //更新订单数据
        order.setTransactionId(transactionId);
        order.setUpdateTime(new Date());
        order.setPayTime(new Date());
        order.setPayStatus("1");
        order.setOrderStatus("1");
        orderMapper.updateByPrimaryKey(order);

        //保存订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOperater("system");
        orderLog.setOperateTime(new Date());
        orderLog.setOrderStatus("1");
        orderLog.setPayStatus("1");
        orderLog.setRemarks("支付流水号：" + transactionId);
        orderLog.setOrderId(orderId);
        orderLogMapper.insert(orderLog);

    }

    @Override
    @Transactional
    public void closeOrder(String orderId) {
        System.out.println("关闭订单开启：" + orderId);
        //查询数据库订单信息
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        if (!"0".equals(order.getOrderStatus())) {
            System.out.println("此订单不用关闭");
            return;
        }

        //调用微信订单查询 检测支付状态
        Map<String, String> wxQueryMap = (Map) wxPayFeign.queryOrder(orderId).getData();
        System.out.println("查询微信支付订单：" + wxQueryMap);

        //如果支付状态是成功 订单状态没完成 则进行补偿
        if ("SUCCESS".equals(wxQueryMap.get("trade_state"))) {
            updatePayStatus(orderId, (String) wxQueryMap.get("transaction_id"));
            return;
        }

        //如果是未支付 则关闭订单
        if ("NOTPAY".equals(wxQueryMap.get("trade_state"))) {
            //关闭微信订单
            wxPayFeign.closeOrder(orderId);
        }

        //本地数据库关闭订单回滚
        System.out.println("执行关闭");

        order.setCloseTime(new Date());
        order.setOrderStatus("4");
        orderMapper.updateByPrimaryKeySelective(order);

        //记录订单变动日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOperater("system");
        orderLog.setOperateTime(new Date());
        orderLog.setOrderStatus("4");
        orderLog.setOrderId(orderId);
        orderLogMapper.insert(orderLog);

        //恢复库存和销量
        OrderItem _orderItem = new OrderItem();
        _orderItem.setOrderId(orderId);
        List<OrderItem> orderItemList = orderItemMapper.select(_orderItem);

        for (OrderItem orderItem : orderItemList) {
            skuFeign.resumeStockNum(orderItem.getSkuId(), orderItem.getNum());
        }
    }

    @Override
    @Transactional
    public void batchSend(List<Order> orders) {
        //判断运单号和物流公司是否为空
        for (Order order : orders) {
            if (order.getId() == null) {
                throw new RuntimeException("订单不存在");
            }
            if (order.getShippingName() == null || order.getShippingCode() == null) {
                throw new RuntimeException("请输入订单号或物流公司名称");
            }
        }

        //循环订单,进行状态校验
        for (Order order : orders) {
            Order order1 = orderMapper.selectByPrimaryKey(order.getId());
            if (!"0".equals(order1.getConsignStatus()) || !"1".equals(order1.getOrderStatus())) {
                throw new RuntimeException("订单状态不合法");
            }
        }

        //循环订单更新操作
        for (Order order : orders) {
            order.setOrderStatus("2");
            order.setConsignStatus("1");
            order.setConsignTime(new Date());
            order.setUpdateTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
            //记录订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperateTime(new Date());
            orderLog.setOperater("admin");
            orderLog.setOrderStatus("2");
            orderLog.setConsignStatus("1");
            orderLog.setOrderId(order.getId());
            orderLogMapper.insertSelective(orderLog);
        }


    }

    @Override
    @Transactional
    public void confirmTask(String orderId, String operator) {

        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        if (!"1".equals(order.getConsignStatus())) {
            throw new RuntimeException("订单未发货");
        }

        order.setConsignStatus("2");//已送达
        order.setOrderStatus("3");//已完成
        order.setUpdateTime(new Date());
        order.setEndTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);

        //记录订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOperateTime(new Date());
        orderLog.setOperater(operator);
        orderLog.setOrderStatus("3");
        orderLog.setConsignStatus("2");
        orderLog.setOrderId(order.getId());
        orderLogMapper.insertSelective(orderLog);

    }

    @Override
    @Transactional
    public void autoTask() {
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        //获取当前时间
        Calendar calendar = Calendar.getInstance();
        //获取过期时间节点
        calendar.add(-orderConfig.getTakeTimeout(), Calendar.DAY_OF_MONTH);
        System.out.println(calendar.getTime());

        //按条件查询
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderStatus", "2");
        criteria.andLessThan("consignTime", calendar.getTime());
        List<Order> orders = orderMapper.selectByExample(example);

        for (Order order : orders) {
            this.confirmTask(order.getId(), "system");
        }
    }

    @Override
    public List<Order> list(String username) {
        Order order = new Order();
        order.setUsername(username);
        List<Order> orderList = orderMapper.select(order);
        if (orderList != null && orderList.size() > 0) {
            OrderItem orderItem = new OrderItem();
            for (Order _order : orderList) {
                orderItem.setOrderId(_order.getId());
                List<OrderItem> orderItemList = orderItemMapper.select(orderItem);
                _order.setOrderItemList(orderItemList);
            }
        }
        return orderList;
    }

    @Override
    @Transactional
    public void receipt(String orderId) {
        //根据orderId找出当前订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"1".equals(order.getPayStatus())) {
            throw new RuntimeException("订单未付款,不能确认收货");
        }
        //如果订单不是已送达状态不能确认收货
        if (!"2".equals(order.getConsignStatus())) {
            throw new RuntimeException("订单未送达,不能确认送货");
        }
        order.setOrderStatus("3");  //订单已完成
        order.setBuyerRate("0");  //收货后订单设置为未评价状态
        order.setEndTime(new Date());
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKey(order);

        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setPayStatus(order.getPayStatus());
        orderLog.setOperateTime(new Date());
        orderLog.setOrderStatus(order.getOrderStatus());
        orderLog.setConsignStatus(order.getConsignStatus());
        orderLog.setOperater("user"); //用户操作
        orderLogMapper.insertSelective(orderLog);
    }

    @Override
    public List<Map<String, String>> findCountByOrderStatus() {
        List<Map<String,String>> list=new ArrayList();
        Map<String,String> map=new HashMap<>();
        map.put("name","待付款订单");
        map.put("value",String.valueOf(orderMapper.findCountByOrderStatus("0")));
        list.add(map);

        Map<String,String> map1=new HashMap<>();
        map1.put("name","待发货订单");
        map1.put("value",String.valueOf(orderMapper.findCountByOrderStatus("1")));
        list.add(map1);

        Map<String,String> map2=new HashMap<>();
        map2.put("name","已发货订单");
        map2.put("value",String.valueOf(orderMapper.findCountByOrderStatus("2")));
        list.add(map2);

        Map<String,String> map3=new HashMap<>();
        map3.put("name","已完成订单");
        map3.put("value",String.valueOf(orderMapper.findCountByOrderStatus("3")));
        list.add(map3);

        Map<String,String> map4=new HashMap<>();
        map4.put("name","已关闭订单");
        map4.put("value",String.valueOf(orderMapper.findCountByOrderStatus("4")));
        list.add(map4);
        return list;
    }

    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> profitCount = new ArrayList<>();
        for (String month : months) {
            String firstDate = month + ".01";
            String lastDate = month + ".31";
            Integer count = orderMapper.findMemberCountBeforeDate(firstDate, lastDate);
            if (count == null) {
                count = 0;
            }
            profitCount.add(count);
        }
        return profitCount;
    }

    public List<Order> findList2Pay(String username) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("payStatus", "0");  //未付款
        criteria.andEqualTo("orderStatus", "0");    //未付款
        List<Order> orderList = orderMapper.selectByExample(example);
        if (orderList != null && orderList.size() > 0) {
            OrderItem orderItem = new OrderItem();
            for (Order _order : orderList) {
                orderItem.setOrderId(_order.getId());
                List<OrderItem> orderItemList = orderItemMapper.select(orderItem);
                _order.setOrderItemList(orderItemList);
            }
        }
        return orderList;
    }

    @Override
    public List<Order> findList2Send(String username) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("payStatus", "1");  //已付款
        criteria.andEqualTo("orderStatus", "1");    //已付款
        criteria.andEqualTo("consignStatus", "0");    //未发货
        List<Order> orderList = orderMapper.selectByExample(example);
        if (orderList != null && orderList.size() > 0) {
            OrderItem orderItem = new OrderItem();
            for (Order _order : orderList) {
                orderItem.setOrderId(_order.getId());
                List<OrderItem> orderItemList = orderItemMapper.select(orderItem);
                _order.setOrderItemList(orderItemList);
            }
        }
        return orderList;
    }

    @Override
    public List<Order> findList2Receive(String username) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("payStatus", "1");  //已付款
        criteria.andEqualTo("orderStatus", "3");    //已付款
        criteria.andEqualTo("consignStatus", "2");    //已送达
        List<Order> orderList = orderMapper.selectByExample(example);
        if (orderList != null && orderList.size() > 0) {
            OrderItem orderItem = new OrderItem();
            for (Order _order : orderList) {
                orderItem.setOrderId(_order.getId());
                List<OrderItem> orderItemList = orderItemMapper.select(orderItem);
                _order.setOrderItemList(orderItemList);
            }
        }
        return orderList;
    }

    @Override
    @Transactional
    public void evaluation(String orderId, String buyerRate, String evaluation) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"3".equals(order.getOrderStatus())) {
            throw new RuntimeException("订单未完成");
        }
        if (!"0".equals(order.getBuyerRate())) {
            throw new RuntimeException("订单已评价");
        }
        order.setBuyerRate(buyerRate);
        order.setBuyerMessage(evaluation);
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public List<Order> findList2Evaluation(String username) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderStatus", "3");    //已完成
        criteria.andEqualTo("buyerRate", "0");    //未评价
        List<Order> orderList = orderMapper.selectByExample(example);
        if (orderList != null && orderList.size() > 0) {
            OrderItem orderItem = new OrderItem();
            for (Order _order : orderList) {
                orderItem.setOrderId(_order.getId());
                List<OrderItem> orderItemList = orderItemMapper.select(orderItem);
                _order.setOrderItemList(orderItemList);
            }
        }
        return orderList;

    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andEqualTo("payType", searchMap.get("payType"));
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andEqualTo("sourceType", searchMap.get("sourceType"));
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andEqualTo("orderStatus", searchMap.get("orderStatus"));
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andEqualTo("payStatus", searchMap.get("payStatus"));
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andEqualTo("consignStatus", searchMap.get("consignStatus"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }
            // 实付金额
            if (searchMap.get("createTime") != null) {
                criteria.andEqualTo("createTime", searchMap.get("createTime"));
            }

        }
        return example;
    }

}
